package com.miya.demo.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.miya.demo.common.annotations.DataMask;
import com.miya.demo.common.enums.DataMaskEnum;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.Objects;

/**
 * @author CaiXiaowei
 * @description 脱敏序列化配置
 * @date 2023/7/20 18:00
 */
@Configuration
public class DataMaskingSerializer extends JsonSerializer<String> implements ContextualSerializer{

    private DataMaskEnum dataMaskEnum;
    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        DataMask annotation = beanProperty.getAnnotation(DataMask.class);
        if(Objects.nonNull(annotation)&& Objects.equals(String.class,beanProperty.getType().getRawClass())){
            this.dataMaskEnum=annotation.function();
            return this;
        }
        return serializerProvider.findValueSerializer(beanProperty.getType(),beanProperty);
    }

    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(dataMaskEnum.function().apply(s));
    }
}
